//
//  NSString+Common.m
//  TimeBoat
//
//  Created by Mac on 2020/3/11.
//  Copyright © 2020yang. All rights reserved.
//

#import "NSString+Common.h"


@implementation NSString (Common)

-(BOOL)hhe_isNotEmpty{
    if (self == nil || self == NULL) {
        return NO;
    }
    if ([self isKindOfClass:[NSNull class]]) {
        return NO;
    }
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return NO;
    }
    if ([self isEqualToString:@"<null>"]) {
        return NO;
    }
    
    if ([self isEqualToString:@"(null)"]) {
        return NO;
    }
    
    return YES;
}


+(BOOL)hhe_isEmpty:(NSString*)str {
    
    if (str == nil) {
        return YES;
    }
    if (![str isKindOfClass:NSString.class]) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    
    if ([str isEqualToString:@"<null>"]) {
        return YES;
    }
    
    if ([str isEqualToString:@"(null)"]) {
        return YES;
    }
    
    return NO;
    
}


- (NSString *)hhe_transToWanYi{
    if (self.intValue < 10000) {
        return self;
    }
    int t = self.intValue / 10000;
    if (t < 10000) {
        return [NSString stringWithFormat:@"%d万",t];
    }
    t /= 10000;
    return [NSString stringWithFormat:@"%d亿", t];
}

- (BOOL)hhe_isMobileNumber{
    NSString *emailRegex = @"^1[3-9]{1}\\d{9}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    return [predicate evaluateWithObject:self];
}

- (BOOL)hhe_isPassWorldLength{
    NSString *emailRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    return [predicate evaluateWithObject:self];
}


- (BOOL)hhe_idCard{
    NSString *idcard = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([idcard length] != 18)
    {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd , @"[0-9]{3}[0-9Xx]"];
    
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:self])
    {
        return NO;
    }
    int summary = ([idcard substringWithRange:NSMakeRange(0,1)].intValue + [idcard substringWithRange:NSMakeRange(10,1)].intValue) *7+ ([idcard substringWithRange:NSMakeRange(1,1)].intValue + [idcard substringWithRange:NSMakeRange(11,1)].intValue) *9+ ([idcard substringWithRange:NSMakeRange(2,1)].intValue + [idcard substringWithRange:NSMakeRange(12,1)].intValue) *10+ ([idcard substringWithRange:NSMakeRange(3,1)].intValue + [idcard substringWithRange:NSMakeRange(13,1)].intValue) *5+ ([idcard substringWithRange:NSMakeRange(4,1)].intValue + [idcard substringWithRange:NSMakeRange(14,1)].intValue) *8+ ([idcard substringWithRange:NSMakeRange(5,1)].intValue + [idcard substringWithRange:NSMakeRange(15,1)].intValue) *4+ ([idcard substringWithRange:NSMakeRange(6,1)].intValue + [idcard substringWithRange:NSMakeRange(16,1)].intValue) *2+ [idcard substringWithRange:NSMakeRange(7,1)].intValue *1 + [idcard substringWithRange:NSMakeRange(8,1)].intValue *6+ [idcard substringWithRange:NSMakeRange(9,1)].intValue *3;
    NSInteger remainder = summary % 11;
    NSString *checkBit = @"";
    NSString *checkString = @"10X98765432";
    checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];
    // 判断校验位
    return [checkBit isEqualToString:[[idcard substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}

+ (NSString *)hhe_getNowTimeTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}

- (NSString *)hhe_timeStampToNowTime{
    NSTimeInterval interval    =[self doubleValue] ;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    formatter.locale = [NSLocale systemLocale];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}

+ (NSString *)hhe_timeStampToNowTimeSSS{
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    return timeSp;
}

- (NSString *)hhe_timeStampToNowTimeWithDateformatter:(NSString *)formatterStr{
    NSTimeInterval interval    = [self doubleValue] ;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterStr];
    formatter.locale = [NSLocale systemLocale];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}


- (NSString *)hhe_gregorianCalendarTimeStampToNowTimeWithDateformatter:(NSString *)formatterStr{
    NSTimeInterval interval    = [self doubleValue] ;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [NSLocale systemLocale];
    NSCalendar *initCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [formatter setCalendar:initCalendar];
    [formatter setDateFormat:formatterStr];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}


- (NSString *)hhe_transToTimeStamp{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //设定时间的格式
    dateFormatter.locale = [NSLocale systemLocale];
    NSDate *tempDate = [dateFormatter dateFromString:self];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

- (NSString *)hhe_getTodayTimestamp{
    NSTimeInterval interval    =[self doubleValue] ;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    formatter.locale = [NSLocale systemLocale];
    NSString *dateString       = [formatter stringFromDate: date];
    NSDate *tempDate           = [formatter dateFromString:dateString];
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]];
    return timeStr;
}

- (NSString *)hhe_updateBeforeTime{
    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] ;
    // 创建歌曲时间戳(后台返回的时间 一般是13位数字)
    NSTimeInterval createTime = self.doubleValue;
    // 时间差
    NSTimeInterval time = currentTime - createTime;
    if (time < 60) {
        return NSLocalizedString(@"刚刚", nil);
    }
    NSInteger minutes = time / 60;
    if (minutes < 60) {
        
        return [NSString stringWithFormat:@"%zi%@", minutes,NSLocalizedString(@"分钟前", nil)];
    }
    // 秒转小时
    NSInteger hours = time / 3600;
    if (hours < 24) {
        return [NSString stringWithFormat:@"%zi%@",hours,NSLocalizedString(@"小时前", nil)];
    }
    // 秒转天数
    NSInteger days = time / 3600 / 24;
    if (days < 30) {
        return [NSString stringWithFormat:@"%zi%@",days,NSLocalizedString(@"天前", nil)];
    }
    /// 超过1个月。
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    formatter.locale = [NSLocale systemLocale];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:createTime];
    NSString *dateString = [formatter stringFromDate: date];
    return dateString;
}

- (NSString *)hhe_updateAfterTime{
    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] ;
    // 创建歌曲时间戳(后台返回的时间 一般是13位数字)
    NSTimeInterval createTime = self.doubleValue;
    // 时间差
    NSTimeInterval time = createTime - currentTime;
    if (time < 0) {
        return @"";
    }
    if (time < 60) {
        return NSLocalizedString(@"现在", nil);
    }
    NSInteger minutes = time / 60;
    if (minutes < 60) {
        
        return [NSString stringWithFormat:@"%zi%@", minutes,NSLocalizedString(@"分钟后", nil)];
    }
    // 秒转小时
    NSInteger hours = time / 3600;
    if (hours < 24) {
        return [NSString stringWithFormat:@"%zi%@%zi%@",hours,NSLocalizedString(@"小时", nil), minutes,NSLocalizedString(@"分钟后", nil)];
    }
    // 秒转天数
    NSInteger days = time / 3600 / 24;
    if (days < 30) {
        return [NSString stringWithFormat:@"%zi%@%zi%@",days,NSLocalizedString(@"天", nil), hours,NSLocalizedString(@"小时后", nil)];
    }
    /// 超过1个月。
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    formatter.locale = [NSLocale systemLocale];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:createTime];
    NSString *dateString = [formatter stringFromDate: date];
    return dateString;
}

- (NSString *)hhe_getTimeWithHHmmFormart{
    // 获取当前时时间戳 1466386762.345715 十位整数 6位小数
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] ;
    // 创建歌曲时间戳(后台返回的时间 一般是13位数字)
    NSTimeInterval createTime = self.longLongValue;
    // 时间差
    NSTimeInterval time = currentTime - createTime;
    if (time < 60) {
        return NSLocalizedString(@"刚刚", nil);
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    formatter.locale = [NSLocale systemLocale];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:createTime];
    NSString *dateString = [formatter stringFromDate: date];
    
    // 秒转小时
    NSInteger hours = time / 3600;
    if (hours < 24) {
        return dateString;
    }else if (hours < 48) {
        return [NSString stringWithFormat:@"今天%@", dateString];
    }
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [formatter stringFromDate: date];
}

- (NSString *)hhe_getMMSSFromSS{
    NSInteger seconds = [self integerValue];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    return format_time;
}

- (BOOL)hhe_comparisonTimeForTimeInterval:(NSString *)otherTimeInterval min:(int)min{
    NSTimeInterval one = self.doubleValue;
    NSTimeInterval two = otherTimeInterval.doubleValue;
    NSTimeInterval time = one>two?one-two:two-one;
    if (time >= (60*min)) {
        return YES;
    }
    return NO;
}

- (CGFloat)hhe_calculateStrWidthwithHigh:(CGFloat)high withFont:(UIFont *)font{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    CGSize labelSize =[self boundingRectWithSize:CGSizeMake(MAXFLOAT, high) options:NSStringDrawingUsesLineFragmentOrigin  attributes:dic context:nil].size;
    return labelSize.width;
}

- (CGFloat)hhe_calculateStrHighWithWidth:(CGFloat)width withFont:(UIFont *)font{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    CGSize labelSize =[self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:dic context:nil].size;
    return labelSize.height;
}

- (NSDictionary *)hhe_jsonStringConvertToDict{
    if (self == nil) {
        return nil;
    }
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err){
        return nil;
    }
    return dic;
}


/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineView:       需要绘制成虚线的view
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向， NO 为垂直方向
 **/
+ (void)drawLineOfDashByCAShapeLayer:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:lineView.bounds];

    if (isHorizonal) {

        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame), CGRectGetHeight(lineView.frame))];

    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame), CGRectGetHeight(lineView.frame)/2)];
    }

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {

        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);

    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }

    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}

///获取当天某点时间戳
+ (NSString *)getTime: (NSInteger)hour andMinute:(NSInteger)minute {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];//[[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [greCalendar setTimeZone: timeZone];

    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:[NSDate date]];
    //  定义一个NSDateComponents对象，设置一个时间点
    NSDateComponents *dateComponentsForDate = [[NSDateComponents alloc] init];
    [dateComponentsForDate setDay:dateComponents.day];
    [dateComponentsForDate setMonth:dateComponents.month];
    [dateComponentsForDate setYear:dateComponents.year];
    [dateComponentsForDate setHour:hour];
    [dateComponentsForDate setMinute:minute];

    NSDate *dateFromDateComponentsForDate = [greCalendar dateFromComponents:dateComponentsForDate];
    NSInteger timeSp = (long)[dateFromDateComponentsForDate timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld",timeSp];
}

+ (NSString *)getOneDateWithHour: (NSInteger)hour andMinute:(NSInteger)minute thatDayTime:(double)thatDayTime{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:thatDayTime];
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];//[[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [greCalendar setTimeZone: timeZone];

    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:date];
    //  定义一个NSDateComponents对象，设置一个时间点
    NSDateComponents *dateComponentsForDate = [[NSDateComponents alloc] init];
    [dateComponentsForDate setDay:dateComponents.day];
    [dateComponentsForDate setMonth:dateComponents.month];
    [dateComponentsForDate setYear:dateComponents.year];
    [dateComponentsForDate setHour:hour];
    [dateComponentsForDate setMinute:minute];

    NSDate *dateFromDateComponentsForDate = [greCalendar dateFromComponents:dateComponentsForDate];
    NSInteger timeSp = (long)[dateFromDateComponentsForDate timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld",timeSp];
}

@end
